package com.caltco.cargo.ops.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.caltco.cargo.ops.modules.sys.dao.UserLevelDao;
import com.caltco.cargo.ops.modules.sys.entity.UserLevel;
import com.caltco.cargo.ops.modules.sys.service.UserLevelService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ScheduledTaskServiceImp {
    private final UserLevelDao userLevelDao;
    private final UserLevelService userLevelService;
    ObjectMapper objectMapper = new ObjectMapper();


    public ScheduledTaskServiceImp(UserLevelDao userLevelDao, UserLevelService userLevelService) {
        this.userLevelDao = userLevelDao;
        this.userLevelService = userLevelService;
    }


    @Scheduled(fixedRate = 60000) // 每60秒执行一次
    public void performTask() {
        System.out.println("定时器");
        List<UserLevel> userLevels = userLevelDao.selectList(new LambdaQueryWrapper<UserLevel>());
        List<UserLevel> insertUserLevels = userLevels.stream()
                .peek(item -> {
                    if (item.getHp() < 6) {
                        item.setHp(item.getHp() + 1);
                    }
                })
                .collect(Collectors.toList());

        userLevelService.updateBatchById(insertUserLevels);

        for (Long userId : WebSocketServer.userSessions.keySet()) {
            UserLevel userLevel = userLevelService.getOne(new LambdaQueryWrapper<UserLevel>()
                    .eq(UserLevel::getUserId, userId));
            try {
                String jsonData = objectMapper.writeValueAsString(userLevel);
                WebSocketServer.sendMessageToUser(userId, jsonData);
                System.out.println("推送数据给用户 " + userId + "：" + jsonData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
